package com.lovely602.langchain4j.functioncalling.service;


import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 *
 * @author lizhixing
 */
@Slf4j
@Component
public class WeatherService {


    @Autowired
    private RestTemplate restTemplate;

    //和风天气开发服务 https://dev.qweather.com/

    // 替换成你自己的和风天气API密钥  凭据ID
    private static final String API_KEY = "T6B8DVHWPA";
    // 调用的url地址和指定的城市，本案例以北京为例
    private static final String BASE_URL = "https://devapi.qweather.com/v7/weather/now?location=%s&key=%s";

    public JsonNode getWeather(String location) throws Exception {

        JsonNode jsonNode = null;
        try {
            //1 传入调用地址url和apikey  101010100
            String url = String.format(BASE_URL, location, API_KEY);

            HttpHeaders headers = new HttpHeaders();
            headers.set("X-QW-Api-Key", API_KEY);
            HttpEntity httpEntity = new HttpEntity<>(headers);

            //2 RestTemplate微服务调用
            String response = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class).getBody();

            //3 解析JSON响应获得第3方和风天气返回的天气预报信息
            jsonNode = new ObjectMapper().readTree(response);
        } catch (Exception e) {
            log.error("查询天气失败:", e);
        }

        //4 想知道具体信息和结果请查看https://dev.qweather.com/docs/api/weather/weather-now/#response
        return jsonNode;
    }

}
